package org.jizp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Processor extends Thread {
	private Socket socket;
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT = "E:\\workspaces\\";
	public Processor(Socket socket){
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		String fileName = parse(in);
		sendFile(fileName);
	}
	
	public String parse(InputStream in){
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httpMessage = bufferedReader.readLine();
			String content[] = httpMessage.split(" ");
			if(content.length != 3){
				sendErrorMessage(400, "Client query error!");
				return null;
			}
			System.out.println("code:" + content[0] + ",fileName:" + content[1] + ",http version:" + content[2]);
			fileName = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	public void sendErrorMessage(int errorCode, String errorMessage){
		out.println("HTTP/1.0 " + errorCode + " " + errorMessage);
		out.println("content-type: text/html");
		out.println("<html>");
		out.println("<title> ErrorMessage");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1> ErrorCode : " +errorCode+" ErrorMessage:"+errorMessage+"</h1>");
		out.println("</body>");
		out.println("</html>");
	}
	
	public void sendFile(String fileName){
		File file = new File(Processor.WEB_ROOT + fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File not found");
		}
		byte[] b = new byte[(int) file.length()];
		try {
			InputStream inputStream = new FileInputStream(file);
			inputStream.read(b);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length:" + file.length());
			out.println();
			out.write(b);
			out.flush();
			out.close();
			inputStream.close();
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}
}
